/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/util/HibernateProxySerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: HibernateProxySerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer.hbm;

import java.io.IOException;
import java.lang.reflect.Type;

import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;

import com.elancom.framework.commons.json.serializer.JSONSerializer;
import com.elancom.framework.commons.json.serializer.JavaBeanSerializer;
import com.elancom.framework.commons.json.serializer.ObjectSerializer;
import com.elancom.framework.commons.json.serializer.SerializeWriter;
import com.elancom.framework.commons.json.serializer.SerializerFeature;

/**
 * @author elancom
 * @date 2012-5-17
 */
public class HibernateProxySerializer implements ObjectSerializer {

	public static final HibernateProxySerializer INSTANCE = new HibernateProxySerializer();

	private HibernateProxySerializer() {
		super();
	}

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
		final SerializeWriter out = serializer.getWriter();

		// lazy process
		if (!Hibernate.isInitialized(object)) {
			if (object instanceof HibernateProxy) {
				out.write("{}");
				out.write(",");

				if (out.isEnabled(SerializerFeature.PrettyFormat)) {
					serializer.println();
				}

				out.writeFieldName("$lazyObject$" + fieldName);
				out.write("true");
			} else {
				out.writeFieldName("$lazyObject$" + fieldName);
				out.write("true");
			}

			return;
		}

		try {
			final org.hibernate.proxy.HibernateProxy proxy = (HibernateProxy) object;
			final Object implementation = proxy.getHibernateLazyInitializer().getImplementation();

			final JavaBeanSerializer javaBeanSerizlizer = new JavaBeanSerializer(implementation.getClass());
			javaBeanSerizlizer.write(serializer, implementation, fieldName, fieldType);
		} finally {
		}
	}

}
